const
	CronJob = require('cron').CronJob,
	uuid = require('uuid/v1'),
	_ = require('lodash'),
	colors = require('colors');

module.exports = function(self, cmd, ...args) {
	let cron = null, cronid = -1;
	switch(cmd){
		case 'create': 
			// 秒分时日月周
			let [time, ...task] = args;
			cron = new CronJob(`*/${time||5} * * * * *`, function(){
				console.log('-- Cron Task --'.green);
				self.rl.write(`${task.join(' ')||batrun}\n`);
			}, null, false, 'Asia/Shanghai');
			cron.id = uuid();
			self.namespace.cron.push({id: cron.id, time: time, task: task.join(' '), started: false, instance: cron});
			console.log(`cron ${cron.id} started.`);
			break;
		case 'start':
			if (args.length == 0) return;
			cronid = args[0];
			// cron = _.find(self.namespace.cron, {id: cronid});
			cron = self.namespace.cron[cronid];
			if (cron) {
				cron.started = true;
				cron.instance.start();
			}
			else console.log(`不存在 ${cronid} 的定时任务。`);
			break;
		case 'stop':
			if (args.length == 0) return;
			cronid = args[0];
			// cron = _.find(self.namespace.cron, {id: cronid});
			cron = self.namespace.cron[cronid];
			if (cron) {
				cron.started = false;
				cron.instance.stop();
				// _.remove(self.namespace.cron,cron);
			}
			else console.log(`不存在 ${cronid} 的定时任务。`);
			break;
		case 'list':
			for(let i in self.namespace.cron){
				cron = self.namespace.cron[i];
				console.log(`定时器 - ${i}: 每${cron.time}秒执行 "${cron.task}"`, cron.started?'已启动'.green.bold:'未启动'.red.bold);
			}
			break;
		default:
			console.log('cron create <time> <task>\ncron start <cron id>\ncron stop <cron id>\ncron list');
			break;
	}
}